﻿using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System;

namespace MSA.Integration
{
    class msa_transformation
    {
        public static string Transform(string inXML, string inXSL)
        {
            return Transform(inXML, inXSL, false);
        }

        public static string Transform(string inXML, string inXSL, bool debugflag)
        {
            XmlDocument sDoc = new XmlDocument();
            sDoc.LoadXml(inXML);
            string timestamp = DateTime.UtcNow.ToString("yyyyMMddhhmmss");
            if (debugflag)
            {
                sDoc.Save(@"c:\debug\source_" + timestamp + ".xml");
            }            
            
            XmlDocument xstyle = new XmlDocument();
            xstyle.LoadXml(inXSL);
            StringWriter writer = new StringWriter();
            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(xstyle);
            
            if (debugflag)
            {
                xstyle.Save(@"c:\debug\style_" + timestamp + ".xslt");
            } 

            xslt.Transform(sDoc, null, writer);
            string response = writer.ToString();

            if (debugflag)
            {
                sDoc.LoadXml(response);
                sDoc.Save(@"c:\debug\target_" + timestamp + ".xml");
            }
           
            //Cleanup - This might start getting big
            writer.Close();
            sDoc = null;
            inXSL = null;
            xstyle = null;
            //End Cleanup
            return response;
        }
    }
}
